package zhexian.app.smartcall;

import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.loveplusplus.update.UpdateChecker;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

import zhexian.app.smartcall.base.BaseActivity;
import zhexian.app.smartcall.base.BaseApplication;
import zhexian.app.smartcall.base.Const;
import zhexian.app.smartcall.call.ContactSQLHelper;
import zhexian.app.smartcall.contact.ContactListFragment;
import zhexian.app.smartcall.image.ZImage;
import zhexian.app.smartcall.lib.DBHelper;
import zhexian.app.smartcall.tools.UploadUtil;
import zhexian.app.smartcall.tools.Utils;
import zhexian.app.smartcall.ui.ProgressFragement;

import static zhexian.app.smartcall.R.layout.sliding_main;

public class MainActivity extends BaseActivity {
    private static final int MSG_BTN_ENABLE_TICK = 0;
    public static final String TAG = MainActivity.class.getSimpleName();
    private static int intro_count_second = 8;
    private Timer mBtnEnableTimer;
    private SlidingMenu menu;

    private ProgressFragement dlgFragment = null;

    public static void actionStart(Activity context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    // TODO 使用弱引用
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Const.UPLOAD_INIT_PROCESS:
                    menu.showContent(true);
                    dlgFragment.setMax(msg.arg1);
                    showProgressDialog();
                    break;
                case Const.UPLOAD_IN_PROCESS:
                    if (dlgFragment.isAdded() && dlgFragment.getShowsDialog()) {
                        ((ProgressDialog) dlgFragment.getDialog()).setProgress(msg.arg1);
                    }
                    break;
                case Const.UPLOAD_FILE_DONE:
                    // TODO 错误处理
                    String result = "响应码：" + msg.arg1 + "\n响应信息：" + msg.obj + "\n耗时：" + UploadUtil.getRequestTime() + "秒";
                    Toast.makeText(MainActivity.this, "头像上传成功！", Toast.LENGTH_LONG).show();
                    if (dlgFragment.isAdded() && dlgFragment.getShowsDialog()) {
                        dlgFragment.dismiss();
                    }

                    ContactListFragment contactListFrag = (ContactListFragment)getFragmentManager().findFragmentById(R.id.main_fragment);
                    if (contactListFrag != null) {
                        contactListFrag.onRefresh();
                    }

                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }

    };

    public Handler getHandler() {
        return handler;
    }

    public void showProgressDialog() {
        if (dlgFragment.isAdded()) {
            return;
        } else {
            dlgFragment.show(this.getFragmentManager(), "ProgressDialog");
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseApplication baseApp = (BaseApplication) getApplication();
        ZImage.Init(baseApp);
        ContactSQLHelper.Init(baseApp);
        DBHelper.init(baseApp.getFileRootDir());

        if (baseApp.getScreenWidth() == 0) {
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            baseApp.setScreenWidth(dm.widthPixels);
            baseApp.setScreenHeight(dm.heightPixels);
        }

        if (baseApp.getAvatarWidth() == 0) {
            //大于1080p，才启用256px的图片
            boolean isHighDisplay = Utils.isHighDisplay(baseApp.getScreenWidth(), baseApp.getScreenHeight());

            if (isHighDisplay)
                baseApp.setAvatarWidth(256);
            else
                baseApp.setAvatarWidth(128);
        }

        if (!baseApp.isLogin()) {
            JumpToLogin();
            return;
        }

        setContentView(R.layout.activity_main);
        bindIntroduce();

        initSlidingMenu();

        Fragment prev = getFragmentManager().findFragmentByTag("ProgressDialog");
        if (prev != null) {
            Log.i(TAG, "找到原来的ProgressDialogFragment");
            dlgFragment = (ProgressFragement)prev;
//            int max = dlgFragment.getArguments().getInt("Max", 0);
//            if (max != 0) {
//                ((ProgressDialog)dlgFragment.getDialog()).setMax(max);
//            }
        } else {
            Log.i(TAG, "创建ProgressDialogFragment");
            dlgFragment = new ProgressFragement();
            dlgFragment.setArguments(new Bundle());
        }

        // 检查版本更新
        if (savedInstanceState == null) {
            UpdateChecker.checkForDialog(MainActivity.this, baseApp.getServiceUrl(Const.URL_CHECK_VERSION));
        }
    }

    private void initSlidingMenu() {
        menu = new SlidingMenu(this);
        menu.setMode(SlidingMenu.LEFT);
        menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        menu.setBehindOffset(400);
        menu.setFadeDegree(0.35f);
        menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        menu.setMenu(sliding_main);
    }

    public void toggleMenu() {
        menu.toggle(true);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        Log.i(TAG, "onSaveInstanceState");
        outState.putBoolean("isMenuShowing", menu.isMenuShowing());
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        Log.i(TAG, "onRestoreInstanceState");
        boolean isMenuShowing = savedInstanceState.getBoolean("isMenuShowing");
        if (isMenuShowing) {
            menu.showMenu();
        }
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, "onDestroy");
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        Log.i(TAG, "onStop");
        super.onStop();
    }

    @Override
    protected void onStart() {
        if (dlgFragment.getArguments() != null){
            int max = dlgFragment.getArguments().getInt("Max", 0);
            Log.i(TAG, "取出的Max=" + max);
            if (max != 0 && dlgFragment.getDialog() != null) {
                ((ProgressDialog) dlgFragment.getDialog()).setMax(max);
            }
        }

        Log.i(TAG, "onStart");
        super.onStart();
    }

    private void bindIntroduce() {
        if (baseApp.isReadIntroduce())
            return;

        final View introView = View.inflate(this, R.layout.flat_intro_window, null);
        final FrameLayout frameLayout = (FrameLayout) findViewById(R.id.contact_main_container);
        frameLayout.addView(introView);
        Utils.GenerateColorAnimator(this, R.animator.intro_window_bg, introView).start();
        TextView mConfirmText = (TextView) findViewById(R.id.intro_confirm_text);
        View mConfirmBtn = findViewById(R.id.intro_confirm_btn);

        mConfirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                frameLayout.removeView(introView);
                baseApp.setIsReadIntroduce(true);
            }
        });
        mConfirmBtn.setEnabled(false);

        mBtnEnableTimer = new Timer();
        final BtnAvailableHandler btnAvailableHandler = new BtnAvailableHandler(mConfirmText, mConfirmBtn, mBtnEnableTimer);

        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                btnAvailableHandler.sendEmptyMessage(MSG_BTN_ENABLE_TICK);
            }
        };
        mBtnEnableTimer.schedule(timerTask, 0, 1000);
    }

    public void JumpToLogin() {
        finish();
        LoginActivity.actionStart(this);
    }

    static class BtnAvailableHandler extends Handler {
        WeakReference<TextView> confirmText;
        WeakReference<View> confirmBtn;
        WeakReference<Timer> btnEnableTimer;

        BtnAvailableHandler(TextView _confirmText, View _confirmBtn, Timer _btnEnableTimer) {
            confirmText = new WeakReference<>(_confirmText);
            confirmBtn = new WeakReference<>(_confirmBtn);
            btnEnableTimer = new WeakReference<>(_btnEnableTimer);
        }

        @Override
        public void handleMessage(Message msg) {
            if (msg.what != MSG_BTN_ENABLE_TICK)
                return;

            TextView _confirmText = confirmText.get();
            View _confirmBtn = confirmBtn.get();
            Timer _btnEnableTimer = btnEnableTimer.get();

            if (_confirmText == null || _confirmBtn == null || _btnEnableTimer == null) {
                if (_btnEnableTimer != null)
                    _btnEnableTimer.cancel();
                return;
            }

            intro_count_second--;

            if (intro_count_second <= 0) {
                _confirmText.setText("知道啦");
                _confirmBtn.setEnabled(true);
                _btnEnableTimer.cancel();
                return;
            }
            _confirmText.setText(String.format("%d秒后可用", intro_count_second));
        }
    }
}
